package ru.gerunn.silent.core;

import java.io.IOException;

import javax.net.ssl.SSLSocket;

import org.apache.log4j.Logger;

import ru.gerunn.silent.io.Reader;
import ru.gerunn.silent.io.ReaderException;
import ru.gerunn.silent.io.SocketReader;
import ru.gerunn.silent.io.SocketWriter;
import ru.gerunn.silent.io.Writer;
import ru.gerunn.silent.io.WriterException;
import ru.gerunn.silent.message.Message;
import ru.gerunn.silent.message.MessageQueue;
import ru.gerunn.silent.message.MessageQueueElement;

public class Session {

	public static Logger log = Logger.getLogger(Session.class);

	private final String id;
	private final SSLSocket socket;
	private final Reader reader;
	private final Writer writer;
	private final User user;
	private final MessageQueue messageQueue;

	public Session(final SSLSocket socket, final User user, final MessageQueue messageQueue) throws SessionException {
		this.id = user.getName();
		this.user = user;
		this.messageQueue = messageQueue;
		this.socket = socket;

		try {
			this.reader = new SocketReader(socket);
		} catch (ReaderException e) {
			throw new SessionException(e);
		}

		try {
			this.writer = new SocketWriter(socket);
		} catch (WriterException e) {
			throw new SessionException(e);
		}
	}

	public void start() throws SessionException {
		Message message = null;
		try {
			while ((message = reader.read()) != null) {
				messageQueue.add(new MessageQueueElement(this, message));
			}
		} catch (ReaderException e) {
			throw new SessionException(e);
		}
	}

	public void close() throws SessionException {
		try {
			socket.close();
		} catch (IOException e) {
			throw new SessionException(e);
		}
	}

	public String getId() {
		return id;
	}

	public Writer getWriter() {
		return writer;
	}

	public User getUser() {
		return user;
	}

}
